//
//  ViewController.m
//  calendar
//
//  Created by Apple on 12/28/15.
//  Copyright © 2015 Apple. All rights reserved.
//

#import "ViewController.h"
#import <EventKit/EventKit.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //事件市场
    NSDate*startData=[NSDate dateWithTimeIntervalSinceNow:5*60];
    NSDate*endDate=[NSDate dateWithTimeIntervalSinceNow:5*120];
    //设置事件之前多长时候开始提醒
    float alarmFloat=-30;
    NSString*eventTitle=@"你该吃药了";
    NSString*locationStr=@"不吃你就GG";
    //isReminder 是否写入提醒事项
    [self saveEventStartDate:startData endDate:endDate alarm:alarmFloat eventTitle:eventTitle location:locationStr isReminder:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)saveEventStartDate:(NSDate*)startData endDate:(NSDate*)endDate alarm:(float)alarm eventTitle:(NSString*)eventTitle location:(NSString*)location isReminder:(BOOL)isReminder{
    //事件市场
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    //6.0及以上通过下⾯面⽅方式写⼊入事件
    if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
        //EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeReminder];

        //等待用户是否同意授权日历
        //EKEntityMaskEvent提醒事项参数（该参数只能真机使用）  EKEntityTypeEvent日历时间提醒参数
        [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error){
                }else if (!granted)
                {
                    UIAlertView *alertView =
                    [[UIAlertView alloc] initWithTitle:@"Access Denied"
                                               message:@"This app doesn't have access to your Reminders." delegate:nil
                                     cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
                    [alertView show];
                    //被⽤用户拒绝,不允许访问⽇日历
                }else{
                    //事件保存到⽇日历
                    //创建事件
                    EKEvent *event = [EKEvent eventWithEventStore:eventStore];
                    event.title = eventTitle;
                    event.location = location;
                    //设定事件开始时间
                    event.startDate=startData;
                    //设定事件结束时间
                    event.endDate=endDate;
                    //添加提醒 可以添加多个，设定事件多久以前开始提醒
                    // event.allDay = YES;
                    //在事件前多少秒开始事件提醒-5.0f
                    [event addAlarm:[EKAlarm alarmWithRelativeOffset:alarm]];
                    EKCalendar *calendar=[eventStore defaultCalendarForNewEvents];
                    calendar.title=@"EXPO";
                    [event setCalendar:calendar];
                    NSError *err;
                    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
                    NSLog(@"保存成功");
                    
                    //是否写入提醒事项，提醒事项为iOS原生自带的，但是模拟器没有的
                    if (isReminder){
                        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
                        [gregorian setTimeZone:[NSTimeZone systemTimeZone]];
                        NSDateComponents *startComponents = [gregorian components:(NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit |
                            NSSecondCalendarUnit) fromDate:startData];
                        
                        NSDateComponents *endComponents = [gregorian components:(NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit |NSHourCalendarUnit | NSMinuteCalendarUnit |
                            NSSecondCalendarUnit) fromDate:endDate];
                        
                        EKCalendar * iDefaultCalendar = [eventStore defaultCalendarForNewReminders];
                        EKReminder *reminder=[EKReminder reminderWithEventStore:eventStore];
                        reminder.startDateComponents=startComponents;
                        reminder.dueDateComponents =endComponents;
                        //reminder.completionDate = [startData dateByAddingTimeInterval:30];
                        iDefaultCalendar.title=@"EXPO";
                        reminder.title=eventTitle;
                        reminder.calendar = iDefaultCalendar;
                        EKAlarm *alarm=[EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeIntervalSinceNow:-10]];
                        [reminder addAlarm:alarm];
                        NSError *error=nil;
                       [eventStore saveReminder:reminder commit:YES error:&error];
                        NSLog(@"保存成功");
                        if (error) {
                            NSLog(@"error=%@",error);
                            
                        }
                        
                    }
                }
                
            });
        }];
        
    }else{
        //4.0和5.0通过下述⽅方式添加 无需判断用户是否同意访问日历
        //事件保存到⽇日历
        //创建事件
        EKEvent *event = [EKEvent eventWithEventStore:eventStore];
        event.title = eventTitle;
        event.location = location;
        //设定事件开始时间
        event.startDate=startData;
        
        //设定事件结束时间
        event.endDate=endDate;
        //添加提醒 可以添加多个，设定事件多久以前开始提醒
        // event.allDay = YES;
        //在事件前多少秒开始事件提醒-5.0f
        [event addAlarm:[EKAlarm alarmWithRelativeOffset:alarm]];
        [event setCalendar:[eventStore defaultCalendarForNewEvents]];
        NSError *err;
        [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
        NSLog(@"保存成功");
        
        //是否写入提醒事项，提醒事项为iOS原生自带的，但是模拟器没有的
        if (isReminder) {
            EKCalendar * iDefaultCalendar = [eventStore defaultCalendarForNewReminders];
            
            EKReminder *reminder=[EKReminder reminderWithEventStore:eventStore];
            reminder.calendar=[eventStore defaultCalendarForNewReminders];
            
            reminder.title=eventTitle;
            reminder.calendar = iDefaultCalendar;
            EKAlarm *alarm=[EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeIntervalSinceNow:-10]];
            [reminder addAlarm:alarm];
            NSError *error=nil;
            
            
            [eventStore saveReminder:reminder commit:YES error:&error];
            if (error) {
                
                NSLog(@"error=%@",error);
                
            }
            
        }
        
    }
}
@end
